package com.hsy.order

import android.app.ActivityManager
import android.content.Context

import com.flux.RxFlux
import com.flux.utils.GlideUtil
import com.flux.utils.LogUtil
import com.hsy.order.base.Consts
import com.tencent.android.tpush.XGPushManager

/**
 * Application
 * Created on 2017/12/1.
 *
 * @language Kotlin
 * @author yang
 */
class Application : android.app.Application() {

    lateinit var rxFlux: RxFlux
        private set

    private val isMainProcess: Boolean
        get() {
            val am = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            val processInfo = am.runningAppProcesses
            val mainProcessName = packageName
            val myPid = android.os.Process.myPid()
            return processInfo.any { it.pid == myPid && mainProcessName == it.processName }
        }

    override fun onCreate() {
        super.onCreate()
        val processName = getProcessName(applicationContext)
        LogUtil.i("=" + processName!!)
        if (Consts.PROCESS_NAME_BIB == processName) {
            instance = this
            GlideUtil.setErrorImageRes(R.mipmap.http_error)

            rxFlux = RxFlux.init(this)

            if (isMainProcess) {
                LogUtil.i("主进程")

                // 为保证弹出通知前一定调用本方法，需要在application的onCreate注册
                // 收到通知时，会调用本回调函数。
                // 相当于这个回调会拦截在信鸽的弹出通知之前被截取
                // 一般上针对需要获取通知内容、标题，设置通知点击的跳转逻辑等等

                XGPushManager.setNotifactionCallback { xGNotification ->
                    LogUtil.i("xg", "处理信鸽通知：$xGNotification")
                    // 如果还要弹出通知，可直接调用以下代码或自己创建Notification，否则，本通知将不会弹出在通知栏中。

                    LogUtil.i("xg", "title：${xGNotification.title}")
                    LogUtil.i("xg", "content：${xGNotification.content}")
                    LogUtil.i("xg", "customContent：${xGNotification.customContent}")

                    xGNotification.doNotify()
                }
            }

        }
    }


    override fun onLowMemory() {
        super.onLowMemory()
        System.gc()
    }

    private fun getProcessName(cxt: Context): String? {
        try {
            val myPid = android.os.Process.myPid()
            val am = cxt.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager?
                    ?: return null
            val runningApps = am.runningAppProcesses ?: return null
            runningApps.filter { it.pid == myPid }.forEach { return it.processName }
        } catch (e: Exception) {
            //
        }

        return null
    }

    companion object {

        init {
            LogUtil.isDebugEnabled = true
        }

        lateinit var instance: Application
            private set
    }
}